package com.pay.dubbo.wx.impl;

import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pay.beans.MobileLrLoginBean;
import com.pay.beans.ReturnBean;
import com.pay.beans.ReturnContent;
import com.pay.beans.WxCustLoginStatusBean;
import com.pay.common.util.PropertyUtil;
import com.pay.common.util.StringUtil;
import com.pay.constants.RedisKeyConstants;
import com.pay.constants.RetConstants;
import com.pay.dubbo.wx.WxCustomerServiceFacade;
import com.pay.mapper.boss.CustomerBossMapper;
import com.pay.mapper.wx.WxCustOperDetailMapper;
import com.pay.mapper.wx.WxCustRelationMapper;
import com.pay.service.WxCustRelationService;
import com.pay.service.WxCustTypeService;
import com.pay.util.HttpClientUtil;
import com.pay.util.RedisCustUtil;
import com.pay.util.RedisUtil;

/**
 * @Description: 商户用户登录服务
 * @see: WxCustomerServiceFacadeImpl 此处填写需要参考的类
 * @version 2016年10月8日 下午4:35:56
 * @author shulin.feng
 */
@Service("wxCustomerServiceFacade")
public class WxCustomerServiceFacadeImpl implements WxCustomerServiceFacade {


	private Log log = LogFactory.getLog(WxCustomerServiceFacadeImpl.class);

	@Resource
	private WxCustRelationMapper wxCustRelationMapper;
	@Resource
	private WxCustOperDetailMapper wxCustOperDetailMapper;
	@Resource
	private CustomerBossMapper customerBossMapper;
	@Resource
	private WxCustTypeService wxCustTypeService;
	@Resource
	private WxCustRelationService wxCustRelationService;
	
	public static final String WEIXIN_LOGIN_SOURCE="weixinLogin";
	
	private static String loginUrl;
	static {
		PropertyUtil propertyUtil = PropertyUtil.getInstance("system");
		loginUrl = propertyUtil.getProperty("com.pay.mobileLr.loginUrl");
	}
	
	@Override
	public ReturnBean logincheck(String username, String password, String openId)
			throws Exception {
		username = username.trim();
		if (username == null) {
			return new ReturnBean(RetConstants.LOGIN_ERROR, RetConstants.LOGIN_ERROR_MSG);
		}
		if (password == null) {
			return new ReturnBean(RetConstants.LOGIN_ERROR, RetConstants.LOGIN_ERROR_MSG);
		}
		return loginWxAndBindCust(username, password, openId );
	}
	
	//https://i.cardinfo.com.cn/mobilelr/loginNew.json?username=13581739218&password=caojian1010&appName=youshua
	/*
	 * {
		    "resultCode": "00",
		    "resultMsg": "",
		    "object": [
		        {
		            "shno": "527616780611485",
		            "ot": "SUPERADMIN",
		            "cn": "8625264187",
		            "userName": "13581739218",
		            "mcc": "9992",
		            "customerName": "个体户曹健",
		            "isPerson": "Y",
		            "phoneMAC": null,
		            "oc": "3902091692",
		            "pk": "ab568774d3015494a29e0105FFFFFFFF",
		            "mk": "74d3012fdd",
		            "isRegister": "N",
		            "lk": "0e656bf9fb0a8ee2f3fa9395a9366bdc"
		        }
		    ]
		}
	 * 
	 */
	private ReturnBean loginWxAndBindCust(String username, String password, String openId) throws Exception {
		// 调用ky登录
		// 测试地址
		// String url = "http://10.10.111.136:8083/mobilelr/login.json";
		String loginResultJson = HttpClientUtil.sendGet(loginUrl,"username=" + username + "&appName=youshua&password=" + password,false,null,null);
		log.info("loginWxAndBindCust 调用登录 resultContent:" + loginResultJson);
		JSONObject result = JSONObject.parseObject(loginResultJson);

		if (result != null) {
			String resultCode = result.getString("resultCode");
			if ("00".equals(resultCode)) {
				List<MobileLrLoginBean> list = JSONArray.parseArray(result.getString("object"), MobileLrLoginBean.class);
				if (null!=list && !list.isEmpty()) {
					Iterator<MobileLrLoginBean> iterator = list.iterator();
					while (iterator.hasNext()) {
						MobileLrLoginBean mobileLrLoginBean = (MobileLrLoginBean) iterator.next();
						if (StringUtils.isBlank(mobileLrLoginBean.getMcc()) 
									|| !mobileLrLoginBean.getMcc().startsWith("999")) {
							//非个人版  禁止使用
							iterator.remove();
						}
					}
					log.info("loginWxAndBindCust username :" + username +"list:" + list.size());
					if (list.size()<1) {
						//无可用商户
						log.info("loginWxAndBindCust username :" + username +"result:" + "无可用商户，无法绑定1");
						return new ReturnBean(RetConstants.LOGIN_ERROR, "无可用商户，无法绑定");
					}else if (list.size()==1) {
						// 校验是否符合绑定条件
						String checkLoginParamResult = checkLoginParam(openId,list.get(0).getCn());
						if (StringUtil.notNull(checkLoginParamResult)) {
							log.info("校验是否符合绑定条件:" + checkLoginParamResult);
							return new ReturnBean(RetConstants.ERROR, checkLoginParamResult);
						}
						wxCustRelationService.createMultBindWxUser(openId, list.get(0).getCn(), list.get(0).getMcc(),WEIXIN_LOGIN_SOURCE );
						log.info("loginWxAndBindCust username :" + username +"result:" + "success");
						return new ReturnBean(RetConstants.SUCCESS, "success");
					}else{
						//多个商户
						log.info("loginWxAndBindCust username :" + username +"result:" + "存在多个商户，无法绑定");
						return new ReturnBean(RetConstants.LOGIN_ERROR, "存在多个商户，无法绑定");
					}
				}else{
					//无可用商户
					log.info("loginWxAndBindCust username :" + username +"result:" + "无可用商户，无法绑定2");
					return new ReturnBean(RetConstants.LOGIN_ERROR, "无可用商户，无法绑定");
				}
			} else {
				log.info("loginWxAndBindCust username :" + username +"result:" + result.get("resultMsg").toString());
				return new ReturnBean(RetConstants.LOGIN_ERROR, result.get("resultMsg").toString());
			}
		} else {
			log.info("loginWxAndBindCust username :" + username +"result:" + RetConstants.LOGIN_ERROR_MSG);
			return new ReturnBean(RetConstants.LOGIN_ERROR, RetConstants.LOGIN_ERROR_MSG);
		}
	}
	

	private String checkLoginParam(String openId, String customerNo) {
		List<WxCustLoginStatusBean> list = RedisCustUtil.getCustByOpenid(openId, false);

		if (list != null) {
			log.info("已绑定用户长度：" + list.size());
			if (list.size() >= 2) {
				return "最多只能绑定1个商户哦";
			}
			for (WxCustLoginStatusBean wxCustLoginStatusBean : list) {
				if (customerNo.equals(wxCustLoginStatusBean.getCustomerNo())) {
					return "此商户已登录过，不需要再次登录哦";
				}
			}
		}
		return null;
	}

	@Override
	public void deleteWxUser(String openId) throws Exception {
		String customerNo = RedisUtil.getValue(RedisKeyConstants.MULT_ACCOUNT_DEFAULT_OPENID_USERNO + openId);
		wxCustRelationService.updateBindStatusByCustomerNo(customerNo,"myself");
	}


	@Override
	public void multBindWxUser(String openId, String customerNo, String mcc, String source) throws Exception {
		wxCustRelationService.createMultBindWxUser(openId, customerNo, mcc, source);
	}


	
	@Override
	public ReturnContent<Object> unbindingCustRelation(String customerNo,
			String channel) {
		ReturnContent<Object> returnContent=wxCustRelationService.updateBindStatusByCustomerNo(customerNo,channel);
		return new ReturnContent<Object>(returnContent.getCode(), returnContent.getMsg());
	}

	@Override
	public void oneKeyRemoveLogoutCustRedis(String idStart, String idEnd,
			String openId,String customerNo) {
		wxCustRelationService.oneKeyRemoveLogoutCustRedis(idStart,idEnd,openId,customerNo);
	}
	
	
}
